import tkinter as tk
from PIL import Image, ImageTk
import os

class ImageViewer:
    def __init__(self, root):
        self.root = root
        self.root.title("Image Viewer")


        # 创建画布
        self.canvas = tk.Canvas(root, width=800, height=600)
        self.canvas.pack()

        self.image = None
        self.photo = None
        self.original_image = None
        self.image_id = None

        from tkinter import filedialog
        
        file_path = os.path.join(os.path.dirname(__file__), "1.jpg")
        
        if os.path.exists(file_path):
            # 打开图片
            self.original_image = Image.open(file_path)
            width, height = self.original_image.size
            # 直接调整原图大小适应画布
            self.original_image.thumbnail((800, 600))
            # 直接使用固定尺寸代替缩略图
            self.original_image = self.original_image.resize((800, 600), Image.LANCZOS)
            self.photo = ImageTk.PhotoImage(self.original_image)
            
            # 显示完整图片并初始化原始尺寸
            self.image_id = self.canvas.create_image(400, 300, anchor=tk.CENTER, image=self.photo)
            
            # 保存初始比例
            self.zoom_level = 1.0
            self.target_zoom = 1.0

            # 初始化检测区域参数
            self.detect_size = 100
            
            # 绘制初始检测框
            self.canvas.create_rectangle(
                400 - self.detect_size/2, 300 - self.detect_size/2,
                400 + self.detect_size/2, 300 + self.detect_size/2,
                outline="#FF0000",
                width=2,
                tags="detect_box"
            )
            
            # 保存原始尺寸和缩放比例
            self.original_width = self.original_image.width
            self.original_height = self.original_image.height
            self.scale_x = self.original_image.width / width
            self.scale_y = self.original_image.height / height

            # 启用放大按钮并绑定鼠标事件

            self.canvas.bind("<Motion>", self.on_mouse_move)
            self.zoom_level = 1.0
            self.target_zoom = 1.0
            self.after_id = None
        else:
            print(f"错误：图片 {file_path} 不存在，请检查路径。")
            root.destroy()

    def on_mouse_move(self, event):
        if self.original_image:
            # 获取图片位置和尺寸
            img_x1, img_y1 = self.canvas.coords(self.image_id)
            img_width = self.photo.width()
            img_height = self.photo.height()

            # 计算原图中心在画布上的坐标
            center_x = 400  # 直接使用画布中心坐标
            center_y = 300

            # 计算实际原图坐标（基于缩放后的图像尺寸）
            img_x = (event.x - (400 - self.original_image.width * self.zoom_level / 2)) / self.zoom_level
            img_y = (event.y - (300 - self.original_image.height * self.zoom_level / 2)) / self.zoom_level

            # 获取图片实际中心坐标
            # 使用原图中心点坐标
            img_center_x = 400
            img_center_y = 300

            # 计算到图片实际中心的距离
            dx = event.x - img_center_x
            dy = event.y - img_center_y
            distance_sq = dx**2 + dy**2
            radius = 100 * self.zoom_level  # 动态缩放基准半径

            # 根据实际像素中心绘制检测框
            img_width = self.original_image.width * self.zoom_level
            img_height = self.original_image.height * self.zoom_level

            # 计算基于原图像素的检测区域
            detect_size = 100 * (1/self.zoom_level)  # 根据缩放级别反向调整检测区域尺寸
            x1 = (img_center_x - detect_size/2)
            y1 = (img_center_y - detect_size/2)
            x2 = (img_center_x + detect_size/2)
            y2 = (img_center_y + detect_size/2)

            self.canvas.delete("detect_box")
            self.canvas.create_rectangle(
                x1, y1,
                x2, y2,
                outline="#FF0000",
                width=2,
                tags="detect_box"
            )

            # 根据鼠标到画布中心的距离计算缩放比例
            base_radius = 100  # 恢复有效基准半径
            # 增大系数，提高缩放比例对鼠标移动的敏感度
            self.target_zoom = min(5.0, max(0.5, 1.0 + (base_radius - (distance_sq**0.5))/base_radius * 0.8))

            # 启动缩放更新
            if not self.after_id:
                self.update_zoom()

    def update_zoom(self):
        # 确保缩放比例不小于 1
        if self.target_zoom < 1:
            self.target_zoom = 1
        if abs(self.zoom_level - self.target_zoom) > 0.01:
            # 增大缩放步长系数，从 0.1 提高到 0.2，可按需调整
            self.zoom_level += (self.target_zoom - self.zoom_level) * 0.2
            print(f"当前缩放: {self.zoom_level:.2f} 目标缩放: {self.target_zoom:.2f}")

            # 计算新尺寸并保持中心点
            new_width = int(self.original_image.width * self.zoom_level)
            new_height = int(self.original_image.height * self.zoom_level)

            # 抗锯齿缩放
            resized_img = self.original_image.resize((new_width, new_height), Image.LANCZOS)
            self.photo = ImageTk.PhotoImage(resized_img)

            # 更新画布并保持中心点
            self.canvas.itemconfig(self.image_id, image=self.photo)
            self.after_id = self.root.after(16, self.update_zoom)
        else:
            self.after_id = None
            # 更新检测框尺寸
            current_size = self.detect_size / self.zoom_level
            # 根据实际缩放后的图像尺寸计算检测框位置
            img_center_x = 400
            img_center_y = 300
            self.canvas.coords("detect_box",
                img_center_x - current_size/2,
                img_center_y - current_size/2,
                img_center_x + current_size/2,
                img_center_y + current_size/2
            )
            print(f"缩放级别: {self.zoom_level:.2f}, 检测框尺寸: {current_size:.1f} 中心坐标: ({img_center_x:.1f}, {img_center_y:.1f})")  # 添加详细坐标输出
            # 移除鼠标移动事件中的动态缩放计算
            

    def zoom_image(self):
        pass  # 保留空方法避免按钮报错

if __name__ == "__main__":
    root = tk.Tk()
    app = ImageViewer(root)
    root.mainloop()